<template>
  <div>
    <el-form ref="formRef" :model="FormData" :rules="FormRules" label-width="100px">
      <el-row>
        <div class="title">
          <div class="title-bar"></div>
          <div>{{ $t('包材信息') }}</div>
        </div>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="sku:" prop="sku">
            <span>{{ FormData.skuNo }}</span>
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(FormData.skuNo)"></i>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('库位号') + ':'">
            <span>{{ FormData.spNo }}</span>
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(FormData.spNo)"></i>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('额外sku') + ':'">
            <span>{{ FormData.skuExtra }}</span>
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(FormData.skuExtra)"></i>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('中文名') + ':'" prop="skuNameCn">
            <el-input disabled v-model="FormData.skuNameCn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('日文名') + ':'" prop="skuNameJp">
            <el-input disabled v-model="FormData.skuNameJp"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('英文名') + ':'" prop="skuNameEn">
            <el-input disabled v-model="FormData.skuNameEn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('商品分类')" prop="classId">
            <treeselect
              disabled
              v-model="FormData.classId"
              :options="menuOptions"
              :show-count="true"
              :placeholder="$t('请选择')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('jan编码') + ':'" prop="janCode">
            <el-input disabled v-model="FormData.janCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('品牌') + ':'" prop="brand">
            <el-input disabled v-model="FormData.brand"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('产品规格') + ':'" prop="specification">
            <el-input disabled v-model="FormData.specification"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('长度') + ':'" prop="skuAttrLength">
            <el-input style="width: 100%" v-model="FormData.skuAttrLength" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('宽度') + ':'" prop="skuAttrWidth">
            <el-input style="width: 100%" v-model="FormData.skuAttrWidth" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('高度') + ':'" prop="skuAttrHeight">
            <el-input style="width: 100%" v-model="FormData.skuAttrHeight" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('重量') + ':'" prop="skuAttrWeight">
            <el-input style="width: 100%" v-model="FormData.skuAttrWeight" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">g</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item :label="$t('箱规') + ':'" prop="box">
            <el-input disabled v-model="FormData.box" />
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1" v-if="FormData.box">
          <el-form-item :label="$t('箱子重量') + ':'" prop="janCode">
            <div class="size">{{ FormData.skuWeight * FormData.box }}g</div>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1">
          <el-form-item
            label-width="90px"
            v-model="FormData.isExpired"
            :label="$t('是否会过期') + ':'"
            prop="isExpired"
          >
            <el-radio-group disabled v-model="FormData.isExpired">
              <el-radio :label="1">{{ $t('是') }}</el-radio>
              <el-radio :label="0">{{ $t('否') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1">
          <el-form-item label-width="120px" :label="$t('最近过期时间') + ':'" prop="latelyExpiredTime">
            <div>{{ FormData.latelyExpiredTime }}</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('备注') + ':'" prop="remark">
            <el-input disabled v-model="FormData.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('采购备注') + ':'" prop="purchaseRemark">
            <el-input disabled v-model="FormData.purchaseRemark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 捆包要求： -->
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('捆包要求') + ':'" prop="bindDemand">
            <el-input v-model="FormData.bindDemand"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button
            type="primary"
            plain
            @click="submitForm"
            v-hasPermi="['distribution:skuDistributor:updateSkuDistributorPackageMaterial']"
          >
            {{ $t('修改') }}
          </el-button>
        </el-form-item>
      </el-row>
      <!-- 捆包图片： -->
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('捆包图片') + ':'" prop="skuNameCn">
            <div class="image-list">
              <ImgUploadManage :businessId="skuId" type="9" :uploadLimit="10" :limit="10" :fileList.sync="fileList" />
            </div>
            <div style="text-align: right">
              <el-button
                v-hasPermi="['distribution:skuDistributor:uploadSkuBindImages']"
                @click="handleUpdateImage"
                size="small"
                plain
                type="primary"
              >
                {{ $t('更新图片') }}
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 关联包材： -->
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('关联包材') + ':'" prop="skuNameCn">
            <div>
              <el-button
                class="mb10"
                v-hasPermi="['distribution:skuConsumablePurchase:bingSkuCes']"
                @click="handleAdd"
                type="success"
                plain
                size="small"
              >
                {{ $t('添加') }}
              </el-button>
              <el-table :data="tableData" border style="width: 100%">
                <el-table-column align="center" prop="cesNo" :label="$t('编号')" />
                <el-table-column align="center" prop="cesName" :label="$t('名字')" />
                <el-table-column align="center" prop="cesImg" :label="$t('图片')">
                  <template slot-scope="{ row }">
                    <el-image
                      style="width: 50px; height: 50px"
                      fit="contain"
                      :key="Math.random()"
                      v-hover="row.cesImg"
                      :src="row.cesImg + '?x-oss-process=image/resize,w_100/quality,q_70'"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="specification" :label="$t('规格')" />
                <el-table-column align="center" prop="num" :label="$t('数量')" />
                <el-table-column align="center" :label="$t('操作')">
                  <template slot-scope="{ row }">
                    <el-button type="text" size="small" @click="handleDelete(row)">
                      <span style="color: red">{{ $t('移除') }}</span>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align: right">
      <el-button @click="cancel">{{ $t('关闭') }}</el-button>
    </div>
    <!-- 添加 -->
    <el-dialog :title="$t('添加')" :visible.sync="addInfo.show" width="500px" append-to-body>
      <el-form ref="addForm" :model="addInfo.form" :rules="addInfo.rules">
        <el-form-item :label="$t('耗材')" prop="cesId">
          <el-select filterable style="width: 100%" clearable v-model="addInfo.form.cesId">
            <el-option
              :label="`${item.cesName}:${item.cesNo}:${item.specification}`"
              :value="item.id"
              :key="item.id"
              v-for="item in skuConsumableList"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('关联数量')" prop="num">
          <el-input style="width: 100%" clearable v-model.number="addInfo.form.num" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdd">{{ $t('确定') }}</el-button>
        <el-button @click="addInfo.show = false">{{ $t('取消') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  bingSkuCes,
  deleteSkuBindImg,
  deleteSkuCes,
  getInfo,
  listNoPageByGoods,
  updateSkuDistributorPackageMaterial,
  saveSkuBindImages,
} from '@/api/distribution/sku/packingInformation'
import { listSkuClassByLanguage } from '@/api/platform/goodsClassDict'
import i18n from '@/language'
import auth from '@/plugins/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { Loading } from 'element-ui'
export default {
  name: 'ErpDistributionSystemPlusPackingInformation',
  components: { Treeselect },

  data() {
    return {
      skuId: this.$parent.$parent.skuInfo.skuId,
      /**商品分类菜单树选项 */
      menuOptions: [],
      /**
       * 新增相关
       */
      addInfo: {
        show: false,
        rules: {
          num: [
            {
              required: true,
              message: this.$t('请选择'),
              trigger: 'blur',
            },
          ],
          cesId: [
            {
              required: true,
              message: this.$t('请选择'),
              trigger: 'blur',
            },
          ],
        },
        form: {
          /**耗材 */
          cesId: '',
          /**关联数量 */
          num: '',
          skuId: this.$parent.$parent.skuInfo.skuId,
          skuNo: this.$parent.$parent.skuInfo.skuNo,
        },
      },
      /**耗材列表 */
      skuConsumableList: [],
      loadingInstance: null,
      fileList: '',
      backFormDate: {},
      FormData: {},
      FormRules: {
        skuAttrLength: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        skuAttrWidth: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        skuAttrHeight: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        skuAttrWeight: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        bindDemand: [{ validator: this.validLength, required: false, trigger: 'change' }],
      },

      tableData: [],
    }
  },
  created() {
    this.getInfo()
    this.$getSkuClassList().then((res) => {
      this.menuOptions = res.menuOptions
    })
  },
  mounted() {},

  methods: {
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value?.length || 0

      // bindDemand
      if (field == 'bindDemand') {
        //  长度最大为 255
        if (strLength > 255) {
          return callback(new Error(`文字超长 ${strLength} / 255`))
        }
      }

      return callback()
    },
    handleDelete(row) {
      this.$confirm(this.$t('确定删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deleteSkuCes(row.id, this.$parent.$parent.skuInfo.skuId).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.getInfo()
          }
        })
      })
    },
    submitAdd() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          bingSkuCes(this.addInfo.form).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })

              this.addInfo.show = false
              this.getInfo()
            }
          })
        }
      })
    },
    handleAdd() {
      this.addInfo.form.cesId = ''
      this.addInfo.form.num = ''
      listNoPageByGoods().then((res) => {
        this.skuConsumableList = res.data
      })
      this.addInfo.show = true
    },
    beforeRemove(file) {
      /**删除权限 */
      const deleteAuth = 'distribution:skuDistributor:deleteSkuBinddwqdqdImg'
      if (!auth.hasPermi(deleteAuth)) {
        this.$message.success('权限不足!')
        return false
      }

      return new Promise((resolve, reject) => {
        console.log(`file,  ==>`, file)
        this.$confirm(i18n.t('确定删除?'), i18n.t('提示'), {
          type: 'warning',
        })
          .then(async () => {
            if (!file.raw) {
              const { code, msg } = await deleteSkuBindImg(file.id)
              if (code === 200) {
                this.$message({ type: 'success', message: msg })

                resolve()
                // this.getInfo();
              }
            }
          })
          .catch((e) => e)
      })
    },
    // 打开遮罩层
    loading(content) {
      this.loadingInstance = Loading.service({
        lock: true,
        text: content,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
    },
    // 关闭遮罩层
    closeLoading() {
      this.loadingInstance.close()
    },
    handleUpdateImage() {
      const formData = new FormData()
      formData.append('imgUrls', this.fileList)
      formData.append('skuId', this.skuId)
      saveSkuBindImages(formData).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })
          this.getInfo()
        }
      })
    },
    // 验证数据是否改变
    validFormData() {
      let FormDataChange = null
      if (JSON.stringify(this.backFormDate) == JSON.stringify(this.FormData)) {
        FormDataChange = false
      } else {
        FormDataChange = true
      }
      return FormDataChange
    },
    getInfo() {
      const skuid = this.$parent.$parent.skuInfo.skuId
      getInfo(skuid).then((res) => {
        this.$parent.$parent.updateSkuImg(res.data.imgUrl)
        this.backFormDate = res.data
        this.tableData = res.data.skuConsumableList || []
        this.FormData = JSON.parse(JSON.stringify(this.backFormDate))
        this.$nextTick(() => {
          this.fileList = res.data.skuBindImgList?.map((i) => i.imgUrl).toString()
          console.log(` this.fileList  ==>`, JSON.parse(JSON.stringify(this.fileList)))
        })
      })
    },
    onChange(file) {
      console.log(`file ==>`, file)
    },
    submitForm() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          updateSkuDistributorPackageMaterial(this.FormData).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })

              this.getInfo()
              // this.cancel()
            }
          })
        }
      })
    },
    cancel() {
      this.$parent.$parent.cancel()
    },
  },
}
</script>

<style lang="scss" scoped>
.image-list {
  width: 100%;
  min-height: 150px;
  border: 1px solid #ccc;
  position: relative;
  display: flex;
  overflow: auto;
  padding: 20px;
  flex-wrap: wrap;

  .img-item {
    margin: 5px;
    width: 120px;
    height: 120px;
    position: relative;
    border-radius: 5px;
    overflow: hidden;

    &:hover {
      .img-mask {
        display: block;
      }
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .img-mask {
      display: none;
      cursor: pointer;
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);

      .delete-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 27px;
        width: 100%;
        height: 100%;
        color: #fff;
      }
    }
  }

  .upload-btn {
    position: absolute;
    bottom: 5px;
    right: 5px;
  }
}

.title {
  display: flex;
  align-items: center;
  height: 17px;
  font-size: 17px;
  margin: 10px 0 20px 0;

  &-bar {
    width: 2px;
    height: 100%;
    margin-right: 5px;
    background: #7b7979;
  }
}
</style>
